﻿using DataAccess.DTO;
using DataAccess.Models;
using Solr;
using Solr.Commons;
using Solr.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccess.Solr
{
  
   public class SolrDLIndexInfoBLL
   {
       static ISolrResponseParser<NamedList, ResponseHeader> binaryResponseHeaderParser = new BinaryResponseHeaderParser();
       static IObjectDeserializer<ProductDLIndex> exampleDeserializer = new ProductDeserializer();
       static ISolrResponseParser<NamedList, QueryResults<ProductDLIndex>> binaryQueryResultsParser = new BinaryQueryResultsParser<ProductDLIndex>(exampleDeserializer);

       static ISolrResponseParser<NamedList, IList<GroupQueryResults<ProductDLIndex>>> GroupByeParser = new BinaryGroupQueryResultsParser<ProductDLIndex>(exampleDeserializer);

       static ISolrQueryConnection<NamedList> Productconnection = null;
       static ISolrQueryOperations<NamedList> Productoperations = null;
       static ISolrResponseParser<NamedList, IDictionary<string, IDictionary<string, IList<string>>>> binaryHighlightingParser = new BinaryHighlightingParser();
       private static string SolrPath = System.Configuration.ConfigurationManager.AppSettings["Solr"];
       static string ProductCollectionName = "product";
       public SolrDLIndexInfoBLL()
       {

       }
       static SolrDLIndexInfoBLL()
       {
           if (Productconnection == null && Productoperations == null)
           {

               Productconnection = new SolrQueryConnection<NamedList>() { ServerUrl = SolrPath };
               Productoperations = new SolrQueryOperations<NamedList>(Productconnection) { ResponseWriter = "javabin" };
           }

       }
       /// <summary>
       /// SolrQuestion反序列化器
       /// </summary>
       public class ProductDeserializer : IObjectDeserializer<ProductDLIndex>
       {
           public IEnumerable<ProductDLIndex> Deserialize(SolrDocumentList result)
           {
               foreach (SolrDocument doc in result)
               {
                   yield return new ProductDLIndex()
                   {

                       auctionId = doc["id"] != null ? long.Parse(doc["id"].ToString()) : 0,
                       //auctionUrl = doc["auctionUrl"] != null ? doc["auctionUrl"].ToString() : "",
                       //biz30day = doc["biz30day"] != null ? int.Parse(doc["biz30day"].ToString()) : 0,
                       couponActivityId = doc["couponActivityId"] != null ? doc["couponActivityId"].ToString() : "",
                       couponAmount = doc["couponAmount"] != null ? float.Parse(doc["couponAmount"].ToString()) : 0,
                       couponTotalCount = doc["couponTotalCount"] != null ? float.Parse(doc["couponTotalCount"].ToString()) : 0,
                       pictUrl = doc["pictUrl"] != null ? doc["pictUrl"].ToString().Contains("http") ? doc["pictUrl"].ToString(): "https:"+doc["pictUrl"].ToString(): "",
                        //原价格
                       zkPrice = doc["zkPrice"] != null ? float.Parse(doc["zkPrice"].ToString()) : 0,

                       //描述
                       //Introduce = doc["Introduce"] != null ? doc["Introduce"].ToString() : "",
                       //类型  前台判断为 2淘宝  1天猫、、、数据库存的是0=淘宝、1=天猫
                       userType = (doc["userType"] != null ? int.Parse(doc["userType"].ToString()) : 0)==0?2:1,
                       //shopTitle = !string.IsNullOrEmpty(doc["shopTitle"].ToString()) ? doc["shopTitle"].ToString() : (int.Parse(doc["DataTypeID"].ToString()) == 0 ? "淘宝商品" : "天猫商品"),
                     
                       title = doc["productname"] != null ? doc["productname"].ToString() : "",
                      // DataTypeID= doc["DataTypeID"] != null ? int.Parse(doc["DataTypeID"].ToString()) : 0
                       //tkRate = doc["tkRate"] != null ? (decimal.Parse(doc["tkRate"].ToString())).ToString("F2") : "0"
                       tkRate = ((float.Parse(doc["tkRate"].ToString()) / 100) * float.Parse(doc["prices"].ToString())).ToString("F2") 
                   };
               }
           }
       }
       /// <summary>
       /// 通过商品ID查询
       /// </summary>
       /// <param name="ProductSpecRelRid"></param>
       /// <returns></returns>
       public ProductDLIndex GetProductIndexByProductInfo(string auctionId)
       {
           ISolrQuery query = new SolrQuery("id:" + auctionId + "");

           var options = new Dictionary<string, ICollection<string>>();

           options.Add("start", new string[] { "0" });
           options.Add("rows", new string[] { "1" });

           var result = Productoperations.Query(ProductCollectionName, "/select", query, options);

           var examples = binaryQueryResultsParser.Parse(result);

           return examples.FirstOrDefault();
       }

       /// <summary>
       /// 通过商品ID组查询
       /// </summary>
       /// <param name="ProductSpecRelRidIds"></param>
       /// <param name="resultCount"></param>
       /// <returns></returns>
       public List<ProductDLIndex> GetProductDetailList(string ProductSpecRelRidIds)
       {
           ISolrQuery query = new SolrQuery(ProductSpecRelRidIds);

           var options = new Dictionary<string, ICollection<string>>();

           options.Add("start", new string[] { "0" });
           options.Add("rows", new string[] { "50" });

           var result = Productoperations.Query(ProductCollectionName, "/select", query, options);

           var examples = binaryQueryResultsParser.Parse(result);

           return examples.ToList();
       }
       public PagingList<ProductDLIndex> GetProductListModelPage(string strWhere, int PageIndex, int PageSize)
       {
           ISolrQuery query = new SolrQuery(strWhere);

           var options = new Dictionary<string, ICollection<string>>();
           int Count = 0;
           options.Add("start", new string[] { PageIndex.ToString() });
           options.Add("rows", new string[] { PageSize.ToString() });
           options.Add("sort", new string[] { "id desc" });
           var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
           var solrDocumentList = (SolrDocumentList)result.Get("response");
           if (solrDocumentList != null)
           {
               Count = (int)solrDocumentList.NumFound;
           }
           var examples = binaryQueryResultsParser.Parse(result);
           PagingList<ProductDLIndex> list = new PagingList<ProductDLIndex>();
           list.CurrentPageList = examples.ToList();
           list.Total = Count;
           return list;
       }
       public PagingList<ProductDLIndex> GetProductList(string strWhere, int PageIndex, int PageSize, string order)
       {
           ISolrQuery query = new SolrQuery(strWhere);

           var options = new Dictionary<string, ICollection<string>>();
           int Count = 0;
           options.Add("start", new string[] { PageIndex.ToString() });
           options.Add("rows", new string[] { PageSize.ToString() });
           options.Add("sort", new string[] { order });
           var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
           var solrDocumentList = (SolrDocumentList)result.Get("response");
           if (solrDocumentList != null)
           {
               Count = (int)solrDocumentList.NumFound;
           }
           var examples = binaryQueryResultsParser.Parse(result);
           PagingList<ProductDLIndex> list = new PagingList<ProductDLIndex>();
           list.CurrentPageList = examples.ToList();
           list.Total = Count;
           return list;
       }

       /// <summary>
       /// 随机获取商品
       /// </summary>
       /// <param name="size">返回商品条数</param>
       /// <returns></returns>
       public List<ProductDLIndex> GetProductRandom(string strWhere, int size)
       {
           ISolrQuery query = new SolrQuery(strWhere);

           var options = new Dictionary<string, ICollection<string>>();

           options.Add("start", new string[] { "0" });
           options.Add("rows", new string[] { size.ToString() });

           int r = new Random().Next(0, 10000);
           options.Add("sort", new string[] { "random_" + r.ToString() + " desc" });
           var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
           var examples = binaryQueryResultsParser.Parse(result);
           return examples.ToList();
       }
   }
}
